package com.okaixz.web.core.interceptor;


import com.alibaba.fastjson2.JSON;
import com.okaixz.client.model.dto.UserDto;
import com.okaixz.client.properties.JwtProperties;
import com.okaixz.client.service.ITokenService;
import com.okaixz.common.client.Result;
import com.okaixz.common.client.exception.CommonErrorCode;
import com.okaixz.common.utils.StringUtils;
import com.okaixz.framework.interceptor.JwtTokenInterceptor;
import com.okaixz.framework.utils.CommonUtils;
import com.okaixz.manager.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenUserInterceptor extends JwtTokenInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private ITokenService tokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("JwtTokenUserInterceptor preHandle进入了===================================");
        if(!(handler instanceof HandlerMethod)){
            //当前拦截到的不是controller方法直接放行
            return true;
        }
        String httpVersion = request.getHeader("protocolVersion");
        BaseContext.setHttpVersion(httpVersion);


        String token = request.getHeader(jwtProperties.getUserTokenName());
//        log.info("interceptor httpVersion="+httpVersion);
//        log.info("interceptor token="+token);
        if (StringUtils.isEmpty(token)) {
            //没有token直接放行
            return true;
        }

        try {
//            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
//            String usrIdStr = claims.get(JwtClaimsConstant.USER_ID).toString();
//            Long usrId = Long.parseLong(usrIdStr);

            UserDto user = tokenService.getTokenUser(token);
            if (user == null) {
                //过期直接放行
                CommonUtils.writeJson(response, JSON.toJSONString(Result.error(CommonErrorCode.PARSE_TOKEN_FAIL)),null);
                return false;
            }
            //没过期延长token过期时间
//            UserDto userDto = tokenService.refreshUserAndToken(user.getUserId());

            BaseContext.setUserId(user.getUserId());
            log.info("取到userId=" + user.getUserId());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        BaseContext.clean();
    }
}
